import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class StatePatternModule {
    private final Scanner scanner = new Scanner(System.in);
    private final List<AgriculturalMachineContext> machineContexts = new ArrayList<>();
    private final FactoryPatternModule factoryModule;

    public StatePatternModule(FactoryPatternModule factoryModule) {
        this.factoryModule = factoryModule;
    }

    public void execute() {
        // 初始化环境类
        if (machineContexts.isEmpty()) {
            for (AgriculturalMachine machine : factoryModule.getMachines()) {
                machineContexts.add(new AgriculturalMachineContext(machine));
            }
        }

        while (true) {
            System.out.println("\n===== 农机状态管理 =====");
            System.out.println("1. 查看农机状态");
            System.out.println("2. 更改农机状态");
            System.out.println("3. 返回主菜单");
            System.out.print("请选择操作(1-3): ");

            int choice = scanner.nextInt();
            scanner.nextLine();  // 消耗换行符

            switch (choice) {
                case 1 -> viewMachineStates();
                case 2 -> changeMachineState();
                case 3 -> { return; }
                default -> System.out.println("无效选择，请重新输入");
            }
        }
    }

    private void viewMachineStates() {
        if (machineContexts.isEmpty()) {
            System.out.println("没有可用的农机设备");
            return;
        }

        System.out.println("\n=== 农机状态 ===");
        for (int i = 0; i < machineContexts.size(); i++) {
            AgriculturalMachineContext context = machineContexts.get(i);
            System.out.println((i + 1) + ". " + context.getMachine().getStatus() +
                    " | 状态: " + context.getState().getStateName());
        }
    }

    private void changeMachineState() {
        viewMachineStates();
        if (machineContexts.isEmpty()) return;

        System.out.print("选择要更改状态的农机编号: ");
        int index = scanner.nextInt() - 1;
        scanner.nextLine();  // 消耗换行符

        if (index < 0 || index >= machineContexts.size()) {
            System.out.println("无效的农机编号");
            return;
        }

        System.out.println("1. 空闲状态");
        System.out.println("2. 工作状态");
        System.out.println("3. 故障状态");
        System.out.print("选择新状态(1-3): ");
        int stateChoice = scanner.nextInt();
        scanner.nextLine();  // 消耗换行符

        MachineState newState;
        switch (stateChoice) {
            case 1:
                newState = new IdleState();
                break;
            case 2:
                newState = new WorkingState();
                break;
            case 3:
                newState = new FaultState();
                break;
            default:
                System.out.println("无效选择");
                return;
        }

        machineContexts.get(index).setState(newState);
    }
}